package com.spring.mvc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * Created by aivin on 2018/1/28.
 */
public class LoginInterceptor implements HandlerInterceptor {

    // 返回值：表示我们是否需要将当前的请求拦截下来
    // 如果返回false： 请求将被终止
    // 如果返回true： 请求将被继续执行
    // 参数：o表示的是被拦截的请求的目标对象
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletRequest.setCharacterEncoding("utf-8");
        System.out.println("执行到了preHandle方法！");

        //对用户是否的登录进行判断
        if (httpServletRequest.getSession().getAttribute("user") == null) {
            //如果用户没有登录，就终止请求，并发送到登录页面
            httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest,httpServletResponse);
            return false;
        }
        return true;
    }


    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // 可以通过ModelAndView参数来改变显示的视图，或发往视图的方法
        System.out.println("执行到了postHandle方法！");
        modelAndView.addObject("msg","这里传回的是被拦截器修改之后的消息");
        modelAndView.setViewName("hometwo");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("执行到了afterCompletion方法！");
    }
}
